import { FormData } from 'formdata-node'
import { readMultipartFormData, getMethod, getCookie } from 'h3'

export default defineEventHandler(async (event) => {
  const { app } = useRuntimeConfig()
  const formData = new FormData()
  const businessType = app['BUS_TYPE']
  const method = getMethod(event).toUpperCase()
  const body = await readMultipartFormData(event)
  if (!body || !body.length) return

  const file = body[0]
  const uploadToken = await $fetch('/user-center/watt/preUploadToken', {
    method,
    baseURL: event.context.baseUrl,
    headers: event.context.headers,
    body: {
      businessType,
      fileKey: file.filename
    }
  })
  if (!uploadToken || uploadToken.code !== 0 || !uploadToken.data) {
    console.error('tokenData error!')
    return
  }
  const { key, token } = uploadToken.data || {}
  formData.set('file', new File([file.data], file.filename, { type: file.type }))
  // formData.set('file', new Blob([file.data], { type: file.type })) // blob 文件名丢失
  formData.set('key', key)
  formData.set('token', token)
  formData.set('x:type', businessType)
  formData.set('x:deviceId', event.context.headers.get('client-id'))
  formData.set('x:uid', getCookie(event, 'OP_ID'))
  await $fetch('https://upload-z2.qiniup.com/', {
    method: 'POST',
    body: formData
  })
  const res = await $fetch('/user-center/setAvatar', {
    method,
    baseURL: event.context.baseUrl,
    headers: event.context.headers,
    body: { avatar: `https://static.jsvue.cn/${key}` }
  })
  return res || {}
})
